package work.zhengyun.demo.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import work.zhengyun.demo.entity.User;
import work.zhengyun.demo.service.PermissionService;
import work.zhengyun.demo.service.RoleService;
import work.zhengyun.demo.service.UserService;

import java.util.Set;

/**
 * @author zhengyun
 * @date 2019/11/26 17:00
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    /**
     * 授权逻辑
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        System.out.println("执行授权逻辑");
        //获取当前用户
        Subject subject= SecurityUtils.getSubject();
        User user=(User)subject.getPrincipal();
        // 获取账号的角色和权限信息
        Set<String> roles = roleService.listRoleName(user);
        Set<String> permissions = permissionService.listPermissionName(user);
        // 授权对象信息
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setStringPermissions(permissions);
        authorizationInfo.setRoles(roles);
        return authorizationInfo;
    }

    /**
     * 认证逻辑
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
        System.out.println("执行认证逻辑");
        // 编写shiro判断逻辑，判断用户名和密码
        System.out.println(arg0.toString());
        // 1. 判断用户名
        UsernamePasswordToken token = (UsernamePasswordToken) arg0;
        User user = userService.findByName(token.getUsername());
        if (user==null) {
            //用户名不存在
            return null;//shiro底层会抛出UnknownAccountException
        }
        // 2. 判断密码
        // 参数1：需要返回给login方法的数据；参数2：数据库密码，shiro会自动判断
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }

}
